package com.gamatechno.solodestination;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.SearchManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.opengl.Visibility;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.ScrollView;
import android.widget.SearchView;
import android.widget.Spinner;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.FacebookError;
import com.facebook.android.SessionStore;
import com.facebook.android.Facebook.DialogListener;
import com.gamatechno.adapter.ImageLoader;
import com.gamatechno.solodestination.model.AppPreferences;
import com.gamatechno.solodestination.model.DBHandler;
import com.gamatechno.solodestination.model.Favorite;
import com.gamatechno.solodestination.model.HttpUtils;
import com.gamatechno.solodestination.model.Komentar;
import com.gamatechno.solodestination.model.Kuliner;

@SuppressLint("ValidFragment")
public class SubKulinerActivity extends FragmentActivity {
	private static final String[] PERMISSIONS = new String[] {
		"publish_stream", "read_stream", "offline_access" };
	public String judul;
	RatingBar rb;
	String tipe = "";
	String Lat, Lon;
	private TabHost mTabHost;
	private View mRoot;
	private ScrollView scrl;
	TextView SubTitle;
	Spinner spin;
	AppPreferences _pref;
	TextView tvdesc;
	ImageView imgHead, imgFav, imgFavRed;
	ImageLoader imgloader;
	TextView tvkategori;
	LinearLayout ll_komentar;
	Button btn_to_post_comentar;
	DBHandler db = new DBHandler(this);
	private static final String APP_ID = "239419142913008";
	private Facebook mFacebook;
	TextView tv_load_komen;
	public SubKulinerActivity(String tipes) {
		tipe = tipes;
	}

	public SubKulinerActivity() {

	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.fragment_subitem);
		Bitmap b = BitmapFactory.decodeResource(getResources(),
				R.drawable.header_img);
		BitmapDrawable bd = new BitmapDrawable(getResources(), b);
		ActionBar ab = getActionBar();
		ab.setBackgroundDrawable(bd);

		mFacebook = new Facebook(APP_ID);
		SessionStore.restore(mFacebook, this);

		LayoutInflater inflater = (LayoutInflater) this
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View v = inflater.inflate(R.layout.actionbar_logo, null);
		ImageView iconMap = (ImageView) findViewById(R.id.iconmap);
		tv_load_komen= (TextView) findViewById(R.id.loading_komentar);
		iconMap.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent i = new Intent(android.content.Intent.ACTION_VIEW, Uri
						.parse("http://maps.google.com/maps?daddr=" + Lat + ","
								+ Lon));
				startActivity(i);
			}
		});
		ab.setCustomView(v);
		ab.setDisplayShowCustomEnabled(true);
		getActionBar().setDisplayHomeAsUpEnabled(true);
		getActionBar().setHomeButtonEnabled(true);
		getActionBar().setTitle("");
		getActionBar().setLogo(R.drawable.ic_home);
		ll_komentar = (LinearLayout) findViewById(R.id.ll_komentar);
		// mTabHost = (TabHost) findViewById(android.R.id.tabhost);
		// mTabHost.setup();
		Intent main = getIntent();
		tipe = main.getExtras().getString("judul");
		Lat = main.getExtras().getString("lat");
		Lon = main.getExtras().getString("lon");

		Log.i("tipe", tipe);
		_pref = new AppPreferences(this);
		SubTitle = (TextView) this.findViewById(R.id.titleSub);
		spin = (Spinner) this.findViewById(R.id.spinner);
		scrl = (ScrollView) this.findViewById(R.id.scrl);
		tvdesc = (TextView) this.findViewById(R.id.tvdesc);
		imgHead = (ImageView) this.findViewById(R.id.imgHead);
		tvkategori = (TextView) this.findViewById(R.id.tvkategori);
		imgFav = (ImageView) this.findViewById(R.id.favImg);
		imgFavRed = (ImageView) this.findViewById(R.id.favImgRed);
		// super.onActivityCreated(savedInstanceState);
		// LocalActivityManager mLocalActivityManager = new
		// LocalActivityManager(
		// this, false);
		// mLocalActivityManager.dispatchCreate(savedInstanceState);
		// mTabHost.setup(mLocalActivityManager);

		imgloader = new ImageLoader(this);

		btn_to_post_comentar = (Button) this.findViewById(R.id.button2);
		btn_to_post_comentar.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				Log.wtf("mfacebook.isSessionValid()",
						mFacebook.isSessionValid() + "");
				if (mFacebook.isSessionValid()) {
					// TODO Auto-generated method stub
					Intent i = new Intent(SubKulinerActivity.this,
							PostKomentarActivity.class);

					// startActivityForResult(i,1);
					i.putExtra("id_kuliner", tipe);
					startActivity(i);
				} else {
					new AlertDialog.Builder(SubKulinerActivity.this)
							.setTitle("")
							.setMessage(
									"Belum terkoneksi dengan facebook. Koneksikan aplikasi dengan facebook sekarang.")
							.setPositiveButton(android.R.string.yes,
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog,
												int which) {
											
											mFacebook.authorize(SubKulinerActivity.this, PERMISSIONS, -1,
													new FbLoginDialogListener());
										}
									})
							.setNegativeButton("No",
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog, int id) {
											// if this button is clicked, just
											// close
											// the dialog box and do nothing
											dialog.cancel();
										}
									})
							.setIcon(android.R.drawable.ic_dialog_alert).show();
				}

			}
		});
		new GetDetailKuliner().execute();
		new GetKomentar().execute();

	}
	private final class FbLoginDialogListener implements DialogListener {
		public void onComplete(Bundle values) {
			SessionStore.save(mFacebook, SubKulinerActivity.this);

			Intent i = new Intent(SubKulinerActivity.this,
					PostKomentarActivity.class);

			// startActivityForResult(i,1);
			i.putExtra("id_kuliner", tipe);
			startActivity(i);
		}

		public void onFacebookError(FacebookError error) {
			Toast.makeText(SubKulinerActivity.this,
					"Facebook connection failed", Toast.LENGTH_SHORT).show();

			//mFacebookBtn.setChecked(false);
		}

		public void onError(DialogError error) {
			Toast.makeText(SubKulinerActivity.this,
					"Facebook connection failed", Toast.LENGTH_SHORT).show();

			//mFacebookBtn.setChecked(false);
		}

		public void onCancel() {
			//mFacebookBtn.setChecked(false);
		}
	}
	
	

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			Intent refresh = new Intent(this, SubKulinerActivity.class);
			startActivity(refresh);
			this.finish();
		}
	}

	private class GetKomentar extends
			AsyncTask<Void, Void, ArrayList<Komentar>> {

		// ProgressDialog dialog = new ProgressDialog(Tab.this);

		protected void onPreExecute() {
			// dialog.setMessage(" Loading... ");
			// dialog.show();
			tv_load_komen.setVisibility(View.VISIBLE);
		}

		@Override
		protected ArrayList<Komentar> doInBackground(Void... params) {
			ArrayList<Komentar> lstkom = new ArrayList<Komentar>();

			String url = "http://sms.gamatechno.com/solo_destination/services/getKuliner.php?method=getcomment&kuliner_id="
					+ tipe + "&format=json";

			Log.i("url", url);
			try {
				HttpUtils u = new HttpUtils();
				String a = u.getContents(url);
				Log.i("content", a);
				JSONObject obj = new JSONObject(a);
				Log.i("JSONObject content length", obj.length() + "");
				String jo = obj.get("result") + "";
				Log.i("isi result", jo + "");
				JSONArray ka = new JSONArray(jo);
				Log.i("result length", ka.length() + "");

				for (int i = 0; i < ka.length(); i++) {
					JSONObject ja = ka.getJSONObject(i);
					Komentar kom = new Komentar();
					kom.setUser_id(ja.getString("user_id"));

					kom.setName(ja.getString("name"));
					kom.setKuliner_id(ja.getString("kuliner_id"));
					kom.setRating(ja.getString("rating"));
					kom.setUser_comment(ja.getString("user_comment"));
					kom.setComment(ja.getString("comment"));

					try {
						String urlfb = "http://graph.facebook.com/"
								+ ja.getString("user_id") + "/";
						String content_urlfb = u.getContents(urlfb);
						JSONObject jobFB = new JSONObject(content_urlfb);
						kom.setName(jobFB.getString("name"));

					} catch (Exception e) {
						// TODO: handle exception
					}

					try {

						String urlImg = "https://graph.facebook.com/"
								+ ja.getString("user_id") + "?fields=picture";
						Log.wtf("urlImg", urlImg);

						String content_urlImg = u.getContents(urlImg);
						Log.wtf("content_urlImg", content_urlImg);
						String imgz = "";

						JSONObject jobImg = new JSONObject(content_urlImg);
						JSONObject jobImg2 = jobImg.getJSONObject("picture");
						JSONObject jobImg3 = jobImg2.getJSONObject("data");
						imgz = jobImg3.getString("url");
						kom.setUrlImg(imgz);
					} catch (JSONException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}

					lstkom.add(kom);

				}

			} catch (Exception e) {
				// e.printStackTrace();
				Log.i("i", e.toString());
			}
			Log.i("lstkom length", lstkom.size() + "");
			return lstkom;

		}

		@Override
		protected void onPostExecute(ArrayList<Komentar> result) {
			// dialog.dismiss();
			setKomentar(result);
			// setSuhu();
			// super.onPostExecute(result);
			tv_load_komen.setVisibility(View.GONE);
		}

		public void setKomentar(ArrayList<Komentar> result) {
			HttpUtils uz = new HttpUtils();
			for (Komentar komentar : result) {
				imgloader = new ImageLoader(SubKulinerActivity.this);
				View v = getLayoutInflater().inflate(R.layout.tab_item, null);
				TextView tv_nama = (TextView) v.findViewById(R.id.tab_nama);
				TextView tv_comment = (TextView) v.findViewById(R.id.tab_text);
				TextView tv_tanggal = (TextView) v.findViewById(R.id.tab_tgl);
				RatingBar rating = (RatingBar) v.findViewById(R.id.tab_rating);
				ImageView img = (ImageView) v.findViewById(R.id.tab_img);
				Log.wtf("komentar.getUrlImg()", komentar.getUrlImg());

				imgloader.DisplayImage(komentar.getUrlImg(), img);

				tv_nama.setText(komentar.getName());
				tv_comment.setText(komentar.getUser_comment());
				tv_tanggal.setText(komentar.getComment());
				float rtg = 0;
				try {
					rtg = Float.parseFloat(komentar.getRating());
				} catch (Exception e) {
					// TODO: handle exception
				}
				rating.setRating(rtg);
				ll_komentar.addView(v);
			}

		}
	}

	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		// _pref = new AppPreferences(this);
		// SubTitle = (TextView) this.findViewById(R.id.titleSub);
		// spin = (Spinner) this.findViewById(R.id.spinner);
		// scrl = (ScrollView) this.findViewById(R.id.scrl);
		// tvdesc = (TextView) this.findViewById(R.id.tvdesc);
		// imgHead = (ImageView) this.findViewById(R.id.imgHead);
		// tvkategori = (TextView) this.findViewById(R.id.tvkategori);
		// super.onActivityCreated(savedInstanceState);
		// LocalActivityManager mLocalActivityManager = new
		// LocalActivityManager(
		// this, false);
		// mLocalActivityManager.dispatchCreate(savedInstanceState);
		// mTabHost.setup(mLocalActivityManager);
		// new GetDetailKuliner().execute();
		// setisi();
	}

	private class GetDetailKuliner extends AsyncTask<Void, Void, Kuliner> {

		ProgressDialog dialog = new ProgressDialog(SubKulinerActivity.this);

		protected void onPreExecute() {
			dialog.setMessage(" Loading... ");
			dialog.show();
		}

		@Override
		protected Kuliner doInBackground(Void... params) {
			Kuliner kul = new Kuliner();
			ArrayList<Kuliner> ark = new ArrayList<Kuliner>();
			String url = "http://sms.gamatechno.com/solo_destination/services/getKuliner.php?method=kulinerdetail&format=json&language="
					+ _pref.getBahasa() + "&id=" + tipe;
			Log.i("url", url);
			try {
				HashMap<String, String> hasash = new HashMap<String, String>();

				HttpUtils u = new HttpUtils();
				String a = u.getContents(url);
				Log.i("content", a);
				JSONObject obj = new JSONObject(a);
				Log.i("JSONObject content length", obj.length() + "");
				String jo = obj.get("result") + "";
				Log.i("isi result", jo + "");
				JSONObject obj2 = new JSONObject(jo);
				Log.i("JSONObject obj2 length", jo.length() + "");
				Log.i("nama", obj2.getString("name") + "");

				Log.i("i", obj2.getString("name"));
				Log.i("i", obj2.getString("description"));
				Log.i("i", obj2.getString("lat"));
				Log.i("i", obj2.getString("lng"));
				Log.i("i",
						"http://sms.gamatechno.com/solo_destination/files/kuliner/"
								+ obj2.getString("images"));
				Log.i("i", obj2.getString("category"));
				Log.i("i", obj2.getString("district_id"));
				Log.i("i", obj2.getString("district"));
				// Log.i("i",obj2.getString("rating"));
				// Log.i("i",obj2.getString("comment"));
				Log.i("i", tipe);

				kul.setName(obj2.getString("name"));
				kul.setId_kuliner(tipe);
				kul.setDescription(obj2.getString("description"));
				kul.setLat(obj2.getString("lat"));
				kul.setLng(obj2.getString("lng"));
				kul.setImg("http://sms.gamatechno.com/solo_destination/files/kuliner/"
						+ obj2.getString("images"));
				kul.setDistrict(obj2.getString("district"));
				kul.setDistrict_id(obj2.getString("district_id"));
				kul.setCategory(obj2.getString("category"));
				kul.setRating(obj2.getString("rating"));
			} catch (Exception e) {
				// e.printStackTrace();
				Log.i("i", e.toString());
			}

			return kul;

		}

		@Override
		protected void onPostExecute(Kuliner kul) {
			dialog.dismiss();
			setisi(kul);
			// setSuhu();
			// super.onPostExecute(result);
		}
	}

	public void setisi(Kuliner kul) {

		SubTitle.setText(kul.getName());
		tvdesc.setText(Html.fromHtml(kul.getDescription()));
		imgloader.DisplayImage(kul.getImg(), imgHead);
		tvkategori.setText(kul.getCategory());

		if (db.cekFav(kul.getId_kuliner())) {
			imgFavRed.setVisibility(View.VISIBLE);
			imgFav.setVisibility(View.GONE);
		} else {
			imgFavRed.setVisibility(View.GONE);
			imgFav.setVisibility(View.VISIBLE);
		}

		final String id_kuliner = kul.getId_kuliner();
		final String name = kul.getName();
		final String category = kul.getCategory();
		final String img = kul.getImg();
		final Double rate = Double.parseDouble(kul.getRating());
		final String comment = kul.getComment();
		imgFav.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Favorite fav = new Favorite();
				fav.setId(id_kuliner);
				fav.setName(name);
				fav.setCategory(category);
				fav.setImg(img);
				fav.setRate(rate);
				fav.setComments(comment);

				db.addFav(fav);
				imgFavRed.setVisibility(View.VISIBLE);
				imgFav.setVisibility(View.GONE);

			}
		});

		imgFavRed.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Favorite fav = new Favorite();
				fav.setId(id_kuliner);
				fav.setName(name);
				fav.setCategory(category);
				fav.setImg(img);
				fav.setRate(rate);
				fav.setComments(comment);
				db.delFav(id_kuliner);
				imgFavRed.setVisibility(View.GONE);
				imgFav.setVisibility(View.VISIBLE);
			}
		});

		// Intent i;
		// i = new Intent(this, Tab.class);
		// //i.putExtra("i", "1");
		// //i.putExtra("id_detail", tipe);
		//
		// TabSpec sp = mTabHost.newTabSpec("Tab1");
		// View viw = getLayoutInflater().inflate(R.layout.tabs_bg,
		// null);
		// TextView tv_tb = (TextView) viw.findViewById(R.id.tabsText);
		// tv_tb.setText("Semua Komentar");
		//
		// sp.setIndicator(viw);
		// sp.setContent(i);
		// try {
		// mTabHost.addTab(sp);
		// } catch (Exception e) {
		// // TODO: handle exception
		// Log.e("error", e.toString());
		// }

		//
		// Intent j;
		// j = new Intent(this, Tab.class);
		// j.putExtra("i", "2");
		// TabSpec sp2 = mTabHost.newTabSpec("Tab2");
		// View viw2 = LayoutInflater.from(this).inflate(
		// R.layout.tabs_bg, null);
		// TextView tv_tb2 = (TextView) viw2.findViewById(R.id.tabsText);
		// tv_tb2.setText("Komentar Teman");
		// sp2.setIndicator(viw2);
		// sp2.setContent(j);
		// mTabHost.addTab(sp2);

		// mTabHost.addTab(sp);

		// scrl.pageScroll(View.FOCUS_UP);

	}

	// SEARCH ICON AND CLICKABLE
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.main, menu);

		// Associate searchable configuration with the SearchView
		SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
		SearchView searchView = (SearchView) menu.findItem(R.id.action_search)
				.getActionView();
		searchView.setSearchableInfo(searchManager
				.getSearchableInfo(getComponentName()));

		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// toggle nav drawer on selecting action bar app icon/title
		// Handle action bar actions click
		switch (item.getItemId()) {
		case R.id.action_search:
			return true;
		case android.R.id.home:
			this.finish();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		// if nav drawer is opened, hide the action items
		SearchView mSearch = (SearchView) menu.findItem(R.id.action_search)
				.getActionView();
		int searchimg = getResources().getIdentifier(
				"android:id/search_button", null, null);
		ImageView v = (ImageView) mSearch.findViewById(searchimg);
		v.setImageResource(R.drawable.ic_action_search);
		// boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
		menu.findItem(R.id.action_search).setVisible(true);
		return super.onPrepareOptionsMenu(menu);
	}

}
